package com.ruoyi.web.controller.project.book;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.project.book.Book;
import com.ruoyi.system.domain.project.book.BookTeacher;
import com.ruoyi.system.domain.project.book.BookVo;
import com.ruoyi.system.service.project.IBookService;
import com.ruoyi.system.service.project.IBookTeacherService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 专著Controller
 * 
 * @author ruoyi
 * @date 2025-07-30
 */
@RestController
@RequestMapping("/project/book")
public class BookController extends BaseController
{
    @Autowired
    private IBookService bookService;
    @Autowired
    private IBookTeacherService bookTeacherService;
    /**
     * 查询专著列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Book book)
    {
        startPage();
        List<Book> list = bookService.selectBookList(book);
        return getDataTable(list);
    }

    /**
     * 导出专著列表
     */
    @Log(title = "专著", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Book book,
                       @RequestParam(required = false) String exportFields)
    {
        List<Book> list = bookService.selectBookList(book);
        List<BookVo> listVo = new ArrayList<>();
        for(Book info : list){
            if (info.getTeachers() != null && !info.getTeachers().isEmpty()) {
                for(BookTeacher teacher : info.getTeachers()){
                    BookVo bookVo = new BookVo();
                    bookVo.setTitle(info.getTitle());
                    bookVo.setPublisher(info.getPublisher());
                    bookVo.setPublicationNumber(info.getPublicationNumber());
                    bookVo.setPublicationReprintDate(info.getPublicationReprintDate());
                    bookVo.setEdition(info.getEdition());
                    bookVo.setAcademicContribution(info.getAcademicContribution());
                    bookVo.setTextbookUsage(info.getTextbookUsage());
                    bookVo.setRemarks(info.getRemarks());
                    bookVo.setUserName(teacher.getUserName());
                    listVo.add(bookVo);
                }
            }
        }
        ExcelUtil<BookVo> util = new ExcelUtil<BookVo>(BookVo.class);
        // 如果传递了导出字段，则进行处理
        if (StringUtils.isNotBlank(exportFields)) {
            // 将逗号分隔的字段转为数组，调用showColumn指定显示字段
            String[] fields = exportFields.split(",");
            util.showColumn(fields); // 关键：使用ExcelUtil已有的showColumn方法
        }
        util.exportExcel(response, listVo, "专著数据");
    }

    /**
     * 获取专著详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bookService.selectBookById(id));
    }

    /**
     * 新增专著
     */
    @Log(title = "专著", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Book book)
    {
        BookTeacher ra = new BookTeacher();
        if(book.getId()!=null){
            ra.setBookId(book.getId());
        }else {
            ra.setBookId(-1L);
        }
        List<BookTeacher> teachers = bookTeacherService.selectBookTeacherList(ra);
        Long currentId = book.getAuthorId() ;
        if(teachers != null && !teachers.isEmpty()){
            for(BookTeacher teacher : teachers){
                if(teacher.getUserId().equals(String.valueOf(currentId))){
                    return error("当前用户已添加过该专著");
                }
            }
        }
        return toAjax(bookService.insertBook(book));
    }

    /**
     * 修改专著
     */
    @Log(title = "专著", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Book book)
    {
        return toAjax(bookService.updateBook(book));
    }

    /**
     * 删除专著
     */
    @Log(title = "专著", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bookService.deleteBookByIds(ids));
    }

    /**
     * 根据关键字查询科研获奖信息
     */
    @GetMapping("/getBookInfoByTitle")
    public AjaxResult getBookInfoByTitle(  String data)
    {
        Book ra = bookService.getBookInfoByTitle(data);
        return success(ra);
    }
}
